package com.sdgakj.rest;

import com.google.common.base.Charsets;
import com.sdgakj.entity.Message;
import com.sdgakj.entity.MessageUser;
import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.enums.EnumIsFrozen;
import com.sdgakj.enums.EnumMsgType;
import com.sdgakj.service.msg.MessageService;
import com.sdgakj.service.msg.MessageUserService;
import com.sdgakj.service.user.UserService;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.MediaTypes;

import java.util.*;

/**
 * @author yrj
 * 2015/11/24
 */
@RestController
@RequestMapping(value = "/api/v1/msg")
public class MsgRestController {

	 private static Logger logger = LoggerFactory.getLogger(MsgRestController.class);
	
	 private static final String PAGE_SIZE = "10";
	
	 @Autowired
	 private MessageUserService messageUserService;
	
	 @Autowired
	 private MessageService messageService;
	 
	 @Autowired
	 private UserService userService;
	
	/**
	 * 获取个人消息列表 
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
	public Map<String, Object> list(@RequestHeader (value = "userData", defaultValue = "") String userData,
			@RequestParam(value = "uid", defaultValue = "0") String uid,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "deltag", defaultValue = "") String deltag){
		logger.info("uid[]:"+uid);
		String resMsg = "请求成功";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		this.checkUser(uid,resMsg,resultMap);
		String device = "4";
		if(StringUtils.isNotBlank(userData)) {
			String metaData = new String(Base64.decodeBase64(userData), Charsets.UTF_8);
            JSONObject jsonObject = JSONObject.fromObject(metaData);
            String comeFrom = jsonObject.get("comeFrom") != null ? jsonObject.get("comeFrom").toString() : "";
			if("android".equals(comeFrom)) {
				device = "1";
			} else if("iOS".equals(comeFrom)) {
				device = "2";
			}
		}
		List<Long> mids = messageService.getMessageByType(Long.parseLong(uid), EnumMsgType.OTHER.getCode(), device, EnumIsDelete.NOTDELETE.getCode());
//		List<Long> mids = messageService.getMessageByCategory(2, device, EnumIsDelete.NOTDELETE.getCode());
		//List<Long> userIds = messageUserService.getMessageUserByMidWithUid(EnumIsDelete.NOTDELETE.getCode(), uid);
		List<Long> userIds = null;
		if(!"0".equals(uid)) {
			userIds = messageUserService.getMessageUserByMidWithUidExceptDel(uid, device);
		}
		boolean flag = false;
		if(mids!=null && mids.size()>0){
			if(userIds!=null && userIds.size()>0){
				flag = mids.removeAll(userIds);
				if(flag==false && mids!=null && mids.size()>0){
					flag = true;
				}
			}else{
				flag = true;
			}
		}
		
		if(flag){
        	if(!mids.isEmpty()){
        		List<MessageUser> tmList = new ArrayList<MessageUser>();
        		for(Long mid:mids){
	        		MessageUser tmUser = new MessageUser();
	        		Message tm = messageService.getMessage(Long.valueOf(mid));
	        		tmUser.setCreatedate(tm.getCreatedate());
	        		tmUser.setUserId(Long.valueOf(uid));
	        		tmUser.setDeltag(EnumIsDelete.NOTDELETE.getCode());
	        		tmUser.setIsread("0");
	        		tmUser.setMessage(new Message(Long.valueOf(mid)));
	        		tmUser.setUpdatedate(new Date());
	        		tmList.add(tmUser);
        		}
        		this.messageUserService.saveList(tmList);
        	}
        }
	    Map<String, Object> searchParams = new HashMap<String,Object>();
        searchParams.put("EQ_customor.id",uid);
        searchParams.put("EQ_deltag", EnumIsDelete.NOTDELETE.getCode());
        Page<MessageUser> page_user = new Page<MessageUser>() {
			
			@Override
			public Iterator<MessageUser> iterator() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public Pageable previousPageable() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public Pageable nextPageable() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public boolean isLast() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public boolean isFirst() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public boolean hasPrevious() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public boolean hasNext() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public boolean hasContent() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public Sort getSort() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public int getSize() {
				// TODO Auto-generated method stub
				return 0;
			}
			
			@Override
			public int getNumberOfElements() {
				// TODO Auto-generated method stub
				return 0;
			}
			
			@Override
			public int getNumber() {
				// TODO Auto-generated method stub
				return 0;
			}
			
			@Override
			public List<MessageUser> getContent() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public boolean isLastPage() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public boolean isFirstPage() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public boolean hasPreviousPage() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public boolean hasNextPage() {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public int getTotalPages() {
				// TODO Auto-generated method stub
				return 0;
			}
			
			@Override
			public long getTotalElements() {
				// TODO Auto-generated method stub
				return 0;
			}
		};
        if(!"0".equals(uid)) {
//        	page_user = messageUserService.getMessage(searchParams, pageNumber, pageSize,"id","desc");
        	page_user = messageUserService.getMessage(searchParams, device, pageNumber, pageSize,"Message.createdate","desc");
        }
        List<MessageUser> list = new ArrayList<MessageUser>();
        if(page_user!=null && page_user.getContent()!=null && page_user.getContent().size()>0){
        	List<MessageUser> userList = page_user.getContent();
			for(MessageUser message:userList){
				Long id = message.getMessage().getId();
				Message truck = messageService.getMessage(id);
				message.setMessage(truck);
				message.setCreatedate(message.getMessage().getCreatedate());
				list.add(message);
			}
		}
        resultMap.put("totalPages", page_user.getTotalPages());
		resultMap.put("totalNumber", page_user.getTotalElements());
		resultMap.put("data", list);
		resultMap.put("resCode", "1");
		resultMap.put("resMsg",resMsg);
		return resultMap;
	}
	
	
	/**
	 * 更新为已读 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "read", method = RequestMethod.POST)
	public Map<String, Object> read(@RequestParam(value = "id", defaultValue = "0") String id,@RequestParam(value = "uid", defaultValue = "0") String uid)
	{
		String resMsg = "请求成功";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		this.checkUser(uid,resMsg,resultMap);
		try{
		    messageUserService.updateReadById(new Long(id));
			resultMap.put("resCode", "1");
			resultMap.put("resMsg",resMsg);
			return resultMap;
		}catch(Exception e){
			resultMap.put("resCode", "0");
			resultMap.put("resMsg","修改失败");
			logger.error(e.getMessage());
			return resultMap;
		}
	}
	
	
	/**
	 * 消息详情
	 * @param mid
	 * @return
	 */
	@RequestMapping(value = "detail", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
	public Map<String, Object> detail(@RequestParam(value = "mid", defaultValue = "0") Long mid){
		logger.info("mid[]:"+mid);
		String resMsg = "请求成功";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Message message = messageService.getMessage(mid);
		resultMap.put("data", message);
		resultMap.put("resCode", "1");
		resultMap.put("resMsg",resMsg);
		return resultMap;
	}
	
	
	/**
	 * 消息删除
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "delmsg", method = RequestMethod.POST)
	public Map<String, Object> delMsg(@RequestParam(value = "ids", defaultValue = "") Long[] ids,@RequestParam(value = "uid", defaultValue = "0") String uid)
	{
		String resMsg = "删除成功";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		this.checkUser(uid,resMsg,resultMap);
		try{
			if(ids!=null && ids.length>0){
				List<Long> list = new ArrayList<Long>();
				for(Long id:ids){
					list.add(id);
				}
				messageUserService.updateReadByIds(list);
			}
			resultMap.put("resCode", "1");
			resultMap.put("resMsg",resMsg);
			return resultMap;
		}catch(Exception e){
			resultMap.put("resCode", "0");
			resultMap.put("resMsg","删除失败");
			logger.error(e.getMessage());
			return resultMap;
		}
	}
	
	public  Map<String, Object> checkUser(String uid,String resMsg,Map<String, Object> resultMap){
		if(!uid.equals("0")){
			User customor =  userService.getUserById(new Long(uid));
			if(customor!=null){
				if(customor.getStatus().equals(EnumIsFrozen.FROZEN.getCode())){
					resMsg = "用户冻结";
					resultMap.put("resCode", "0");
					resultMap.put("resMsg",resMsg);
				}
			}else{
				resMsg = "用户不存在(id:" + uid + ")";
				resultMap.put("resCode", "0");
				resultMap.put("resMsg",resMsg);
			}
		}
		return resultMap;
	}
	
}
